<template>
	<div class="login_box">
		<h1>登&nbsp;&nbsp;&nbsp;&nbsp;录</h1>

		<div style="margin-top: 100px">
			<el-form :model="userInfo">
				<el-form-item label="用户名：">
					<el-input v-model="userInfo.username" placeholder="请输入用户名"></el-input>
				</el-form-item>
				<el-form-item label="密码：">
					<el-input v-model="userInfo.password" placeholder="请输入用密码" show-password></el-input>
				</el-form-item>
				<el-form-item>
					<el-link href="/register" style="float: left" type="primary">注册账号</el-link>
				</el-form-item>

				<el-form-item>
					<el-button @click="login()" style="width: 100%" type="primary">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	export default {
		name: "Login",
		data() {
			return {
				userInfo: {
					username: "",
					password: ""
				}
			}
		},
		methods: {
			login() {
				if (this.userInfo.username == "" || this.userInfo.password == "") {
					this.$message({
						showClose: true,
						message: '用户名密码不能为空',
						type: 'warning'
					});
					return
				}

				this.$axios.post('/user/login', {
					'username': this.userInfo.username,
					'password': this.userInfo.password
				}).then((result) => {
					if (result.data.code != 100) {
						this.$message({
							showClose: true,
							message: result.data.message,
							type: 'error'
						})
						return
					}
					console.log(result.data.data)
					localStorage.setItem('bingo_username', result.data.data.username)
					localStorage.setItem('bingo_userId', result.data.data.id)
					localStorage.setItem('bingo_avatarUrl', result.data.data.avatarUrl)
					localStorage.setItem('bingo_description', result.data.data.description)
					localStorage.setItem('bingo_cookie', result.data.data.bingo_cookie)
					this.$router.push('/')
				}).catch((err) => {
					console.log(err)
				})
			}
		},
		created() {
			var bingo_cookie = localStorage.getItem('bingo_cookie')
			if (bingo_cookie != null) {
				this.$axios({
					url: '/user/checklogin',
					method: 'post',
					headers: {
						'bingo_cookie': bingo_cookie
					}
				}).then((result) => {
					if (result.data.data == 1) {
						this.$router.push('/')
					} else {
						localStorage.removeItem('bingo_username')
						localStorage.removeItem('bingo_userId')
						localStorage.removeItem('bingo_avatarUrl')
						localStorage.removeItem('bingo_description')
						localStorage.removeItem('bingo_cookie')
					}
				}).catch((err) => {
					localStorage.removeItem('bingo_username')
					localStorage.removeItem('bingo_userId')
					localStorage.removeItem('bingo_avatarUrl')
					localStorage.removeItem('bingo_description')
					localStorage.removeItem('bingo_cookie')
					console.log(err)
				});
			}
		}
	}
</script>

<style scoped>
	.login_box {
		width: 30%;
		margin-left: auto;
		margin-right: auto;
		text-align: center;
	}
</style>